package com.cnu.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cnu.common.JwtUtil;
import com.cnu.sys.entity.User;
import com.cnu.sys.mapper.UserMapper;
import com.cnu.sys.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lmq
 * @since 2023-09-06
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public Map<String, Object> login(User user) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername, user.getUsername());
        User newUser = this.baseMapper.selectOne(wrapper);

        if (newUser != null && passwordEncoder.matches(user.getPassword(), newUser.getPassword())) {
            newUser.setPassword(null);
            String token = jwtUtil.createToken(newUser);
            Map<String, Object> data = new HashMap<>();
            data.put("token", token);
            return data;
        }
        return null;
    }

    @Override
    public Map<String, Object> getUserInfo(String token) {
        User loginUser = null;
        try {
            loginUser = jwtUtil.parseToken(token, User.class);
        } catch (Exception e) {
            e.printStackTrace();
        }

        if(loginUser != null){
            Map<String, Object> res = new HashMap<>();
            res.put("username", loginUser.getUsername());
            res.put("id", loginUser.getId());
            return res;
        }
        return null;
    }

    @Override
    public void logout(String token) {

    }


}
